package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;

import com.sky.service.OrderService;

import com.sky.service.UserService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper  shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper  ;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override//接单
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {

       Orders orders =  Orders.builder()
               .id(ordersConfirmDTO.getId())
               .status(Orders.CONFIRMED)
               .build();
       orderMapper.update(orders);

    }

    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //判断各种业务异常（订单地址为空，购物车为空）
        //订单地址为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            //抛出业务异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //购物车为空
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if(list == null || list.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //插入订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(userId);//用户id
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setPayStatus(Orders.UN_PAID);//未支付
        orders.setStatus(Orders.PENDING_PAYMENT);//待付款
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//订单号
        orders.setPhone(addressBook.getPhone());//手机号
        orders.setConsignee(addressBook.getConsignee());//收货人
        orderMapper.insert(orders);


        //插入订单表数据

        List<OrderDetail> orderDetailList = new ArrayList<>();
        for(ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();   //创建订单详情对象
            BeanUtils.copyProperties(cart, orderDetail);//拷贝
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        //批量插入订单详情数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清空购物车数据
        shoppingCartMapper.delete(userId);
        //封装订单VO数据并返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();


        return orderSubmitVO;
    }

    @Override
    public PageResult pageQuery4User(Integer page, Integer pageSize, Integer status) {
        //设置分页
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        //查询分页结果
       Page<Orders> pageResult = orderMapper.pageQuery4User(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();//订单VO列表
        //查询订单信息，封装成VO
        if(pageResult != null && pageResult.size() > 0) {
            for (Orders orders : pageResult) {
                //获取订单id
                Long orderId = orders.getId();

            //根据订单id查询订单详情
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orderId);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            list.add(orderVO);
        }
        }
        return new PageResult(pageResult.getTotal(), list);
    }
     //取消订单
    @Override
    public void cancel(Long id) throws Exception {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);

       // 校验订单是否存在
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6取消
        if(orders.getStatus() > 2){
            //只有待付款、待接单的订单用户端才可取消
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //订单处于待接单状态下可以取消，需要进行退款
        if(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
           /* //调用微信支付接口，退款
            weChatPayUtil.refund(orders.getNumber(),//订单号
                    orders.getNumber(), //退款订单号
                    orders.getAmount(), //退款金额
                    orders.getAmount());//原订单金额*/

            //支付状态改为退款
            orders.setPayStatus(Orders.REFUND);
            //更新订单状态、取消原因、取消时间
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("用户取消");
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        }





    }
    //查询订单
    @Override
    public OrderVO getOrderDetail(Long id) {
        Orders orders = orderMapper.getById(id);
        // 校验订单是否存在
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;

    }

    @Override
    //再来一单
    public void repetition(Long id) {
        //查询当前用户的id
        Long userid = BaseContext.getCurrentId();
        //根据订单id查询订单详情数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        //将订单详情对象转化为购物车对象
        List<ShoppingCart> shoppingCartsList = orderDetailList.stream().map(
                x -> {
                    ShoppingCart shoppingCart = new ShoppingCart();
                    //将原有的订单信息里面的菜品重新复制到购物车对象中
                    BeanUtils.copyProperties(x, shoppingCart);
                    shoppingCart.setUserId(userid);
                    shoppingCart.setCreateTime(LocalDateTime.now());
                    return shoppingCart;
                }).collect(Collectors.toList());
        //将该购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartsList);


    }

    @Override
    //管理端订单分页查询
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page= orderMapper.pageQuery4User(ordersPageQueryDTO);
        //获取部分订单状态，需要额外返回订单信息，将Orders转化为OrderVO
        List<OrderVO> list = getOrderVOList(page);
        return new PageResult(page.getTotal(), list);

    }

    @Override
    public OrderStatisticsVO statistics() {
        //统计订单数据,根据订单状态来统计数量
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //待接单
        Integer toBeConfirmed = orderMapper.countStatus4Order(Orders.TO_BE_CONFIRMED);
        //待派送
        Integer confirmed = orderMapper.countStatus4Order(Orders.CONFIRMED);
        //派送中
        Integer deliveryInProgress = orderMapper.countStatus4Order(Orders.DELIVERY_IN_PROGRESS);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        //查询订单
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        //只有订单状态为待接单才可被拒
        if (orders == null ||!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //支付状态
        Integer payStatus = orders.getPayStatus();
        //如果支付状态为已支付,则要退款
        if(payStatus == Orders.PAID){
          /*  String refund = weChatPayUtil.refund(
                    orders.getNumber(),//订单号
                    orders.getNumber(),//退款订单号
                    new BigDecimal(0.01),//退款金额
                    new BigDecimal(0.01));//订单金额
            log.info("申请退款返回结果：{}",refund);*/
            //根据id修改订单状态，订单原因，取消时间


        }
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);



    }

    @Override
    public void cancel1(Long id) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
           /* //调用微信支付退款接口
            weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);*/
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }


    @Override
    //订单派送
    public void delivery(Long id) {
        //根据id查询订单信息
        Orders orders = orderMapper.getById(id);
        //判断是否存在和订单状态,只有订单状态为3才能进行派送
        if(orders == null||orders.getStatus() != Orders.CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //订单派送,订单状态转为4
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);

    }

    @Override
    public void complete(Long id) {
        //根据id查询订单信息
        Orders ordersDB = orderMapper.getById(id);
        //订单状态判断,只有订单状态为4才能进行完成订单
        if(ordersDB == null||ordersDB.getStatus() != Orders.DELIVERY_IN_PROGRESS){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //完成订单派送,订单状态转为5
        Orders  orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);

    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

       /* //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );*/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");

        /*if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }*/

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        //根据订单号和用户id查询订单
        Orders orders = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);
        //支付成功后，更新订单状态
        paySuccess(orders.getNumber());
        ///通过websocket发送消息给客户端
        Map map = new HashMap();
        map.put("type",1);//1.表示来单提醒2.表示用户催单
        map.put("orderId",orders.getId());
        map.put("content","订单号"+orders.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);



        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);





    }
    //用户催单
    @Override
    public void reminder(Long id) {
        //根据id查询订单信息
        Orders ordersDB = orderMapper.getById(id);
        //订单状态判断,只有订单状态为2才能进行催单
        if(ordersDB == null||ordersDB.getStatus() != Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //通过websocket发送消息给客户端
        Map map = new HashMap();
        map.put("type",2);//1.表示来单提醒2.表示用户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号"+ordersDB.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        //获取返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> list = new ArrayList<>();
        List<Orders> orderList = page.getResult();
        if(!CollectionUtils.isEmpty(orderList)){
            for (Orders orders : orderList) {
                //将共同的值复制到OrderVO中
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                //获取订单菜品信息,拼接字符串
                String orderDishes = getOrderDishesStr( orders);
                //添加地址
                orderVO.setAddress(getAddress(orders.getAddressBookId()));
                //将订单信息封装到OrderVO中，添加到list中
                orderVO.setOrderDishes(orderDishes);
                list.add(orderVO);
                
            }


        }


        return list;
    }

    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> list = orderDetailMapper.getByOrderId(orders.getId());
        //将订单菜品信息进行拼接，如：宫保鸡丁*2、辣子鸡丁*1
        List<String> orderList = list.stream().map(x -> {
            String orderDishes = x.getName() + "*" + x.getNumber();
            return orderDishes;

        }).collect(Collectors.toList());
        //将该订单的菜品信息拼接在一起，并返回
        return String.join(" ", orderList);
    }
    private String getAddress(Long addressBookId){
      AddressBook addressBook =  addressBookMapper.getById(addressBookId);
      if(addressBook == null){
          return "";
      }
      String address = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
      return address;
    }


}
